package com.sxfq.loansupermarket.backsystem.modular.theTest.controller;

import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.User;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.system.transfer.UserDto;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.TestQuestionsInfo;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.TheTestInfo;
import com.sxfq.loansupermarket.backsystem.modular.theTest.entity.UserForTestInfo;
import com.sxfq.loansupermarket.backsystem.modular.theTest.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 进入考试入口
 *
 * @author py
 * @Date 2018年2月4日23:05:54
 */
@Controller
@RequestMapping("/testModel")
public class TestModelController extends BaseController {
    @Autowired
    ITestModelService iTestModelService;

    @Autowired
    ITestingService iTestingService;

    @Autowired
    ITheTestService iTheTestService;

    @Autowired
    ICompletedTestService completedTestService;

    @Autowired
    IIncompleteTestService iIncompleteTestService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private SqlMapper sqlMapper;

    @RequestMapping("/recite")
    public String recite(Model model) {
        return "/theTest/testModel/recite.html";
    }

    @RequestMapping(value = "/isCanTest", method = RequestMethod.GET)
    @ResponseBody
    public Double isCanTest() throws Exception {
        String sql1 = "select a.the_test_score from user a where id='" + ShiroKit.getUser().getId() + "' limit 1";
        UserDto userDto = sqlMapper.selectOne(sql1, UserDto.class);
        return userDto.getTheTestScore();
    }

    @RequestMapping("/random")
    public String random(Model model) {
        String sql = "select * from the_test_info a where a.the_test_name='咿呀模拟考试'";
        TheTestInfo theTestInfos = sqlMapper.selectOne(sql, TheTestInfo.class);
        TheTestInfo theTestInfo = new TheTestInfo();
        if (iTheTestService.selectTestStatus(theTestInfos.getId(), ShiroKit.getUser().getId()) == 0) {
            theTestInfo = iTestingService.testGenerate(theTestInfos.getId());
        } else {
            theTestInfo = iIncompleteTestService.selectOneById(theTestInfos.getId());
        }
        List<UserForTestInfo> list = completedTestService.selectDetails(theTestInfos.getId(), ShiroKit.getUser().getId());
        long remainingTime = 0;
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(list.get(0).getStartTime());
        Calendar currentTime = Calendar.getInstance();
        currentTime.setTime(new Date());
        long startSecond = startTime.getTimeInMillis();
        long currentSecond = currentTime.getTimeInMillis();
        long totleSecond = Integer.parseInt(theTestInfo.getTimeLength()) * 60;
        remainingTime = (totleSecond - (currentSecond - startSecond) / 1000);
//        remainingTime = Integer.parseInt(ShiroKit.getSessionAttr("timeLength")) * 60;
        if (remainingTime >= 0) {
            model.addAttribute("remainingTime", remainingTime);
            model.addAttribute("times", formatTime(remainingTime));
        } else {
            model.addAttribute("remainingTime", 0);
            model.addAttribute("times", "00:00:00");
        }
        List<TestQuestionsInfo> getList = iTestingService.getList(theTestInfo.getId(), ShiroKit.getUser().getId());
        model.addAttribute("testQuestionsInfoListl", getList.size());
        model.addAttribute("currentPage", getList.get(0).getCurrentPage());
        model.addAttribute("testQuestionsInfoList", getList);
        model.addAttribute("totalScore", theTestInfo.getTotalScore());
        model.addAttribute("theTestId", theTestInfo.getId());
        model.addAttribute("numberOfQuestion", theTestInfo.getNumberOfQuestion());
        model.addAttribute("scoresOfQuestion", theTestInfo.getScoresOfQuestion());
        model.addAttribute("theTestName", theTestInfo.getTheTestName());
        model.addAttribute("timeLength", theTestInfo.getTimeLength());
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        model.addAttribute("userName", user.getName());
        model.addAttribute("userId", ShiroKit.getUser().getId());
        return "/theTest/testModel/random.html";
    }

    @RequestMapping("/test")
    public String test(Model model) {
        String sql = "select * from the_test_info a where a.the_test_name='咿呀正式正畸考试'";
//        String sql = "select * from the_test_info a where a.the_test_name='咿呀正式全科考试'";
        TheTestInfo theTestInfos = sqlMapper.selectOne(sql, TheTestInfo.class);
        TheTestInfo theTestInfo = new TheTestInfo();
        if (iTheTestService.selectTestStatus(theTestInfos.getId(), ShiroKit.getUser().getId()) == 0) {
            theTestInfo = iTestingService.testGenerate(theTestInfos.getId());
        } else {
            theTestInfo = iIncompleteTestService.selectOneById(theTestInfos.getId());
        }
        List<UserForTestInfo> list = completedTestService.selectDetails(theTestInfos.getId(), ShiroKit.getUser().getId());
        long remainingTime = 0;
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(list.get(0).getStartTime());
        Calendar currentTime = Calendar.getInstance();
        currentTime.setTime(new Date());
        long startSecond = startTime.getTimeInMillis();
        long currentSecond = currentTime.getTimeInMillis();
        long totleSecond = Integer.parseInt(theTestInfo.getTimeLength()) * 60;
        remainingTime = (totleSecond - (currentSecond - startSecond) / 1000);
//        remainingTime = Integer.parseInt(ShiroKit.getSessionAttr("timeLength")) * 60;
        if (remainingTime >= 0) {
            model.addAttribute("remainingTime", remainingTime);
            model.addAttribute("times", formatTime(remainingTime));
        } else {
            model.addAttribute("remainingTime", 0);
            model.addAttribute("times", "00:00:00");
        }
        List<TestQuestionsInfo> getList = iTestingService.getList(theTestInfo.getId(), ShiroKit.getUser().getId());
        model.addAttribute("testQuestionsInfoListl", getList.size());
        model.addAttribute("testQuestionsInfoList", getList);
        model.addAttribute("currentPage", getList.get(0).getCurrentPage());
        model.addAttribute("totalScore", theTestInfo.getTotalScore());
        model.addAttribute("theTestId", theTestInfo.getId());
        model.addAttribute("numberOfQuestion", theTestInfo.getNumberOfQuestion());
        model.addAttribute("scoresOfQuestion", theTestInfo.getScoresOfQuestion());
        model.addAttribute("theTestName", theTestInfo.getTheTestName());
        model.addAttribute("timeLength", theTestInfo.getTimeLength());
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        model.addAttribute("userName", user.getName());
        model.addAttribute("userId", ShiroKit.getUser().getId());
        return "/theTest/testModel/test.html";
    }

    @RequestMapping("/error")
    public String error(Model model) {
        Integer id = ShiroKit.getUser().getId();
        User user = userMapper.selectById(id);
        model.addAttribute("userName", user.getName());
        model.addAttribute("userId", ShiroKit.getUser().getId());
        return "/theTest/testModel/error.html";
    }


    private String getDailyInterestRate(String dailyInterestRate) {
        if (dailyInterestRate.indexOf(".") > 0) {
            //正则表达
            dailyInterestRate = dailyInterestRate.replaceAll("0+?$", "");//去掉后面无用的零
            dailyInterestRate = dailyInterestRate.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
        }
        return dailyInterestRate;
    }

    public String formatTime(Long totleSecond) {
        Long hour = totleSecond / 3600;
        Long minute = (totleSecond % 3600) / 60;
        Long second = totleSecond % 60;
        String hours = formatTimeNumber(hour);
        String minutes = formatTimeNumber(minute);
        String seconds = formatTimeNumber(second);
        return hours + ":" + minutes + ":" + seconds;
    }

    public String formatTimeNumber(Long number) {
        if (number < 10) {
            return "0" + number;
        } else {
            return number + "";
        }
    }
}
